#include "tcp_client.h"
#include "lwip.h"
#include "lwip/sockets.h"
#include "system.h"
#include "string.h"
#define LOG_TAG "TCP_Client"

#define SERVER_IP "192.168.1.71" 
#define SERVER_PORT 5000
#define SEND_INTERVAL_MS 2000
#define CLIENT_STACK_SIZE   512
#define CLIENT_TAKS_PRIORITY     5
#define MAX_RETRIES 3
TaskHandle_t TCP_Client_Handle = NULL;

static const char send_buf[] = "hellohellohellohellohellohello"; // 30字节

/**
 * @brief  TCP客户端任务（Socket API）
 */
static void tcp_client_task(void *arg)
{
    int sockfd = -1;
    struct sockaddr_in serv_addr;
    int retry_count = 0;

    // 设置服务器地址
    memset(&serv_addr, 0, sizeof(serv_addr));
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_port = htons(SERVER_PORT);
    inet_pton(AF_INET, SERVER_IP, &serv_addr.sin_addr);
    log_w("TCP client started");
    while (1)
    {
        // 1. 创建socket
        sockfd = socket(AF_INET, SOCK_STREAM, 0);
        if (sockfd < 0)
        {
            log_e("Socket creation failed (errno=%d)", errno);
            goto reconnect;
        }

        // 2. 连接服务器
        log_i("Connecting to %s:%d...\n", SERVER_IP, SERVER_PORT);
        if (connect(sockfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0)
        {
            log_e("Connection failed (errno=%d)", errno);
            close(sockfd);
            goto reconnect;
        }

        log_w("Connected!");
        retry_count = 0; // 重置重试计数器

        // 3. 数据发送循环
        while (1)
        {
            int bytes_sent = send(sockfd, send_buf, sizeof(send_buf) - 1, 0);

            if (bytes_sent <= 0)
            {
                log_e("Send failed (errno=%d)", errno);
                break;
            }

            log_i("Sent %d bytes", bytes_sent);
            vTaskDelay(SEND_INTERVAL_MS);
        }

        // 4. 清理连接
        lwip_close(sockfd);

    reconnect:
        // 5. 重连逻辑（指数退避）
        retry_count++;
        if (retry_count >= MAX_RETRIES)
        {
            log_w("Max retries reached, waiting...\n");
            retry_count = 0;
            vTaskDelay(500);
        }
        else
        {
            vTaskDelay(1000 * retry_count); // 1s, 2s, 3s...
        }
    }
}

/**
 * @brief  初始化TCP客户端
 */
void tcp_client_init(void)
{
    // 确保网络已就绪
    while (!netif_is_up(&gnetif))
    {
        vTaskDelay(100);
    }
    taskENTER_CRITICAL();
    xTaskCreate((TaskFunction_t)tcp_client_task,     // 任务函数
                (const char *)"tcp_Client",          // 任务名称
                (uint16_t)CLIENT_STACK_SIZE,         // 任务堆栈大小
                (void *)NULL,                        // 任务参数
                (UBaseType_t)CLIENT_TAKS_PRIORITY,   // 任务优先级
                (TaskHandle_t *)&TCP_Client_Handle); // 任务句句柄
    taskEXIT_CRITICAL();
}
